package com.lyun.typeHandler;


import com.baomidou.mybatisplus.autoconfigure.SpringBootVFS;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({List.class})
@Component
public class VarcharToStringListlTypeHandler implements TypeHandler<List<String>> {

    //private final String URI = "随便写的URI";


    @Override
    public void setParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setString(i, null);
        } else {
            StringBuilder sb = new StringBuilder();
            for (String str : parameter) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(str);
            }
            ps.setString(i, sb.toString());
        }
    }

    @Override
    public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
        String strValue = rs.getString(columnName);
        return convertStringToList(strValue);
    }

    @Override
    public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String strValue = rs.getString(columnIndex);
        return convertStringToList(strValue);
    }

    @Override
    public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String strValue = cs.getString(columnIndex);
        return convertStringToList(strValue);
    }

    private List<String> convertStringToList(String strValue) {
        List<String> list = new ArrayList<>();
        if (strValue != null) {
            String[] strArray = strValue.split(",");
            for (String str : strArray) {
                //list.add(URI + str);
                list.add(str);
            }
        }
        return list;
    }
}
